package common.gson;

import java.io.IOException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import common.StringUtils;

public class BookTypeAdapter extends TypeAdapter {

	@Override
	public Book read(JsonReader in) throws IOException {
		final Book book = new Book();

	    in.beginObject();
	    while (in.hasNext()) {
	      switch (in.nextName()) {
	      case "isbn":
	        book.setIsbn(in.nextString());
	        break;
	      case "title":
	        book.setTitle(in.nextString());
	        break;
	      case "authors":
	        book.setAuthors(in.nextString().split(";"));
	        break;
	      }
	    }
	    in.endObject();

	    return book;
	}

	@Override
	public void write(JsonWriter out, Object obj) throws IOException {
		
		Book book = (Book)obj;
		out.beginObject();
	    out.name("isbn").value(book.getIsbn());
	    out.name("title").value(book.getTitle());
	    out.name("authors").value( book.getAuthors().toString() );
	    out.endObject();
 
	}

 
}
